package com.ixiaowo.springcouldconsumermovie.controller;


import com.google.common.collect.Lists;
import com.ixiaowo.springcouldconsumermovie.entity.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.loadbalancer.LoadBalancerClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.util.Arrays;
import java.util.List;

@RestController
public class MoiveController {
    /**注入模板*/
    @Autowired
    private RestTemplate restTemplate;
    @Resource
    private LoadBalancerClient loadBalancerClient;

    /**
     * 消费微服务
     * @param id
     * @return
     */
    @GetMapping("/movie/{id}")
    public User findById(@PathVariable Long id){
      return  this.restTemplate.getForObject("http://microservice-provider-user/simple/"+id, User.class);
    }

    /**
     * 获取 地址
     * @return
     */
    @GetMapping(value = "/test")
    public String test(){
        ServiceInstance serviceInstance =  this.loadBalancerClient.choose("microservice-provider-user");
        System.out.println(serviceInstance.getHost()+":"+serviceInstance.getPort()+":"+serviceInstance.getServiceId());
        return "OK....";
    }

    /**
     * 调用服务获取 用户信息列表
     * @return
     */
    @GetMapping("user-all")
    public List<User> getUserAll(){
        //注意restTemplate只能接受 数据  否则会报错
        User[] users = restTemplate.getForObject("http://microservice-provider-user/user-all", User[].class);
        List<User> list = Arrays.asList(users);
        for (User user :list){
            System.out.println(user.getUsername());
        }
        return list;
    }
}
